<?php

namespace app\admin\controller\device;

use app\admin\model\litestore\Litestoregoodsspec;
use app\admin\model\User;
use app\common\controller\Backend;
use fast\Http;
use OSS\Core\OssException;
use OSS\OssClient;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use think\Exception;

/**
 * 设备信息管理
 *
 * @icon fa fa-circle-o
 */
class Device extends Backend
{

    /**
     * Device模型对象
     * @var \app\admin\model\Device
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Device;

    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('user')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {

                if ($v['online_status'] == 1) {
                    $list[$k]['online_status'] = "在线";
                } else {
                    $list[$k]['online_status'] = "离线";
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    public function import()
    {

        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $sql = "SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = " . $table . " AND TABLE_SCHEMA = " . $database;

        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }


            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if ($k !== '') {
                        if ($k == '主板编号') $k = 'device_sn';
                        if ($k == '手机号') $k = 'mobile';
                        if ($k == '设备类型') $k = 'device_type';

                        $row[$k] = $v;
                    }
                }
                if ($row) {
                    $insert[] = $row;
                }
            }

            $userModel = new User();
            $deviceSlotModel = new \app\admin\model\Deviceslot();
            $lastDevice = $this->model->order('id', 'desc')->limit(1)->select();
            $device_id = $lastDevice[0]['device_id'];
            foreach ($insert as $key => $val) {

                $device = $this->model->where('device_sn', $val['device_sn'])->find();
                if (!$device) {
                    $device_id = $device_id + 1;
                    $id = $this->model->insertGetId(['device_sn' => $val['device_sn'], 'device_type' => $val['device_type'], 'device_id' => $device_id, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")]);
                    $deviceSlotModel->add60Slot($device_id);

                } else {
                    $device_id = $device['device_id'];
                    $id = $device['id'];
                }
                if ($val['mobile'] != "") {
                    $user = $userModel->where('mobile', $val['mobile'])->find();
                    $this->model->where('id', $id)->update(['agent_id' => $user['id']]);
                }

                $config = get_addon_config('qrcode');
                $params['text'] = "http://test.51fxyf.com/" . $device_id;
                $params['label'] = $device_id;
                $qrCode = \addons\qrcode\library\Service::qrcode($params);


                $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
                if (!is_dir($qrcodePath)) {
                    @mkdir($qrcodePath);
                }
                if (is_really_writable($qrcodePath)) {

                    if ($device['qr_code'] == '') {

                        $filePath = $qrcodePath . md5(implode('', $params)) . '.' . $config['format'];
                        $qrCode->writeFile($filePath);
                        $config2 = get_addon_config('alioss');
                        $oss = new OssClient($config2['accessKeyId'], $config2['accessKeySecret'], $config2['endpoint']);
                        $name = md5(implode('', $params)) . '.' . $config['format'];
                        $ret = $oss->uploadFile($config2['bucket'], $name, $filePath);
                        $this->model->where('id', $id)->update(['qr_code' => "/" . $name]);

                    }

                }

            }


        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        $this->success();


    }

    public function download()
    {


        $deviceModel = new \app\admin\model\Device();


        $ids = $this->request->param('ids');

        if ($ids == "") {
            $list = $deviceModel->where('create_time', ">=", date("Y-m-d") . " 00:00:00")->where('create_time', "<=", date("Y-m-d") . " 23:59:59")->select();
        } else {
            $ids = explode(",", $ids);
            $list = $deviceModel->where('id', 'in', $ids)->select();
        }

        $img_array = array();
        foreach ($list as $key => $val) {
            $obj = array();
            $obj['id'] = $val['device_id'];
            $obj['url'] = substr($val['qr_code'], 1);
            $img_array[] = $obj;
        }
        try {
            //  设置作品下载或保存目录
            $loaclPath = ROOT_PATH . 'public/zip';
            if (!is_dir($loaclPath)) {
                @mkdir($loaclPath);
            }
            //  目录不存在则进行创建
            //if (!is_dir($loaclPath)) mkdir($loaclPath, 0777, true);
            //  OSS数据内容,不包含bucket名称
            //  定义本地图片数组
            $img = [];

            foreach ($img_array as $k => $v) {
                $object = $v['url'];
                //  获取oss文件地址，不包含bucket名称
                $filename = '/' . $v['id'];
                //    文件后缀
                $ext = substr($object, stripos($object, '.'));
                //  设置文件全名
                $fullPath = $loaclPath . $filename . $ext;

                //  调用oss下载文件
                $this->downLoadOss($object, $fullPath);

                $img[] = $fullPath;
            }

            $name =date("YmdHi").".zip";
            //这里需要注意该目录是否存在，并且有创建的权限
            $fileName = ROOT_PATH . 'public/zip/'.$name;

            $zip = new \ZipArchive();
            $res = $zip->open($fileName, \ZipArchive::CREATE);
            if ($res === TRUE) {

                foreach ($img as $file) {
                    //这里直接用原文件的名字进行打包，也可以直接命名，需要注意如果文件名字一样会导致后面文件覆盖前面的文件，所以建议重新命名
                    $new_filename = substr($file, strrpos($file, '/') + 1);
                    $zip->addFile($file, $new_filename);
                }
            }
            //关闭文件
            $zip->close();

            //  这里是下载zip文件
            ob_end_clean();

            header("Access-Control-Allow-Origin: *"); // 允许任意域名发起的跨域请求
            header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With');
            header("Content-Type: application/force-download");//告诉浏览器强制下载
            header("Content-Transfer-Encoding: binary");//声明一个下载的文件
            header('Content-Type: application/zip');//设置文件内容类型为zip
            header('Content-Disposition: attachment; filename=' . $name);//声明文件名
            header('Content-Length: ' . filesize($fileName));//声明文件大小

            readfile($fileName);
            flush();
            exit;

        } catch (\Exception $e) {
            echo $e->getMessage();
        }


    }


    public function downLoadOss($object, $downPath)
    {


        //下载地址
        $options = array(
            OssClient::OSS_FILE_DOWNLOAD => $downPath
        );

        $config2 = get_addon_config('alioss');
        $ossClient = new OssClient($config2['accessKeyId'], $config2['accessKeySecret'], $config2['endpoint']);
        $ossClient->getObject($config2['bucket'], $object, $options);
        return true;


    }
}
